<?php

namespace App\Services;

use App\Models\Role;
use Illuminate\Support\Facades\DB;

class RoleService
{
    /**
     * 创建角色
     *
     * @param array $data
     * @return Role
     */
    public function create(array $data): Role
    {
        return DB::transaction(function () use ($data) {
            $role = Role::create([
                'name' => $data['name'],
                'code' => $data['code'],
                'status' => $data['status'],
                'sort' => $data['sort'] ?? 0,
                'remark' => $data['remark'] ?? null,
            ]);

            if (isset($data['menu_ids']) && is_array($data['menu_ids'])) {
                $role->menus()->sync($data['menu_ids']);
            }

            if (isset($data['permission_ids']) && is_array($data['permission_ids'])) {
                $role->permissions()->sync($data['permission_ids']);
            }

            return $role->load(['menus', 'permissions']);
        });
    }

    /**
     * 更新角色
     *
     * @param Role $role
     * @param array $data
     * @return Role
     */
    public function update(Role $role, array $data): Role
    {
        return DB::transaction(function () use ($role, $data) {
            $role->update([
                'name' => $data['name'],
                'code' => $data['code'],
                'status' => $data['status'],
                'sort' => $data['sort'] ?? 0,
                'remark' => $data['remark'] ?? null,
            ]);

            if (isset($data['menu_ids']) && is_array($data['menu_ids'])) {
                $role->menus()->sync($data['menu_ids']);
            }

            if (isset($data['permission_ids']) && is_array($data['permission_ids'])) {
                $role->permissions()->sync($data['permission_ids']);
            }

            return $role->load(['menus', 'permissions']);
        });
    }

    /**
     * 删除角色
     *
     * @param Role $role
     * @return bool
     */
    public function delete(Role $role): bool
    {
        return DB::transaction(function () use ($role) {
            $role->menus()->detach();
            $role->permissions()->detach();
            return $role->delete();
        });
    }

    /**
     * 构建查询
     *
     * @param array $filters
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function buildQuery(array $filters = [])
    {
        $query = Role::with(['menus', 'permissions']);

        if (isset($filters['name'])) {
            $query->where('name', 'like', '%' . $filters['name'] . '%');
        }

        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        return $query->orderBy('sort')->orderBy('id', 'desc');
    }
}

